using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace ConsoleApp1
{
	class Server
	{
		static Socket socket = null;
		static void Main(string[] args)
		{
			socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

			EndPoint endPoint = new IPEndPoint(IPAddress.Any, 50000);
			socket.Bind(endPoint);

			socket.Listen(50);

			while (true)
			{
				Socket client = socket.Accept();
				Thread th = new Thread(new ParameterizedThreadStart(SendMessage));
				th.Start(client);

				new Thread(new ParameterizedThreadStart(ReceiveMessage)).Start(client);
				Console.WriteLine(client.RemoteEndPoint.ToString() + "接入服务器");
			}


		}

		private static void SendMessage(object client)
		{
			Socket clientSocket = client as Socket;
			clientSocket.Send(Encoding.Unicode.GetBytes(Console.ReadLine()));

			SendMessage(client);
		}

		private static void ReceiveMessage(object obj)
		{
			Socket socket = obj as Socket;
			byte[] buffer = new byte[1024];
			int length = socket.Receive(buffer);
			Console.WriteLine(socket.RemoteEndPoint.ToString() + " : " + Encoding.Unicode.GetString(buffer, 0, length));

			ReceiveMessage(obj);
		}
	}
}
